package com.aifast.system.sys.entity;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aifast.common.cache.util.RedisUtil;
import com.aifast.common.global.Const;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * @Author fujian
 * @since 2022/1/16 14:50
 *
 * 用户信息封装累 真累
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo implements Serializable {

    private static final long serialVersionUID = -7310748530205797173L;

    /**
     * 用户基础信息
     */
    private Integer userId;
    private String realName;
    private String username;
    private String phone;
    private String email;
    private String avatar;
    private String address;
    private String remarks;
    private String label;
    private Integer tenantId;

    /**
     * 部门信息
     */
    private Integer orgId;
    private String orgName;

    /**
     * 角色信息 按权限优先级排序
     */
    private List<SysRole> roles;
    private List<String> authorities;


    /**
     * 数据权限
     */
    private String dataScope;

    /**
     * 登录信息
     */
    private String token;
    private String device;
    private String admin;

    /*public static UserInfo getMask(){
        List<SysRole> sysRoles = new ArrayList<>();
        SysRole sysRole = new SysRole();
        sysRole.setId(1);
        sysRoles.add(sysRole);
        return UserInfo.builder().userId(392).remarks("天上地下唯吾独尊")
                .address("牛头村").label("除了帅一无所有").device("PC").orgName("一番队")
                .roles(sysRoles)
                .orgId(10)
                .build();
    }*/

    /**
     * 获取当前用户信息
     * @return
     */
    public static UserInfo get(){
        return get(Convert.toStr(StpUtil.getLoginId()));
    }

    public static void remove(){
        remove(Convert.toStr(StpUtil.getLoginId()));
    }

    public static void removeByRole(Integer roleId){
        Set<String> keys = RedisUtil.keys(StrUtil.join(Const.EMPTY, Const.AUTH_PREFIX, "*"));
        if(keys.size() == 0){
            return;
        }

        /*for (String key : keys){
            UserInfo userInfo = JSONUtil.toBean(Convert.toStr(RedisUtil.get(key)), UserInfo.class);
            List<Integer> collect = userInfo.getRoles().stream().map(SysRole::getId).collect(Collectors.toList());
            if(collect.contains(roleId)){
                remove(userInfo.getUserId().toString());
            }
        }*/
    }

    public static void removeByAuthorities(String authority){
        Set<String> keys = RedisUtil.keys(StrUtil.join(Const.EMPTY, Const.AUTH_PREFIX, "*"));
        if(keys.size() == 0){
            return;
        }

        for (String key : keys){
            String s = RedisUtil.get(key);
            UserInfo userInfo = JSONUtil.toBean(s, UserInfo.class);

            if(userInfo.getAuthorities().contains(authority)){
                remove(userInfo.getUserId().toString());
            }
        }
    }

    /**
     * 从缓存中获取
     * @param userId 用户id
     * @return
     */
    public static UserInfo get(String userId){
        String key = StrUtil.join(Const.SYMBOL_COLON,Const.AUTH_PREFIX,userId);
        if(!RedisUtil.exists(key)){
            return null;
        }
        String s = RedisUtil.get(key);
        return JSONUtil.toBean(s, UserInfo.class);
    }

    /**
     * 从缓存中删除
     * @param userId 用户id
     * @return
     */
    public static Boolean remove(String userId){
        try {
            String key = StrUtil.join(Const.SYMBOL_COLON,Const.AUTH_PREFIX,userId);
            RedisUtil.del(key);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 创建缓存
     * @param one 用户
     * @param org 机构
     * @param roles 角色
     * @param authorities 权限
     */
    public static UserInfo init(SysUser one,SysOrg org,List<SysRole> roles,List<String> authorities){
        UserInfo build = UserInfo.builder()
                .userId(one.getId()).realName(one.getRealName()).username(one.getUsername()).email(one.getEmail()).phone(one.getPhone()).avatar(one.getAvatar()).label(one.getLabel()).address(one.getAddress()).remarks(one.getRemarks()).admin(one.getAdmin())
                .roles(roles).authorities(authorities)
                .orgId(ObjectUtil.isNotNull(org) ? org.getId() : 0).orgName(ObjectUtil.isNotNull(org) ? org.getFullName() : Const.EMPTY)
                .token(StpUtil.getTokenValue()).device(StpUtil.getLoginDevice())
                .tenantId(one.getTenantId())
                .build();
        if (StrUtil.equals("1", build.getAdmin())) {
            build.getAuthorities().add(Const.WILDCARD);
        }
        String key = StrUtil.join(Const.SYMBOL_COLON, Const.AUTH_PREFIX, one.getId());
        RedisUtil.set(key, JSONUtil.toJsonStr(build), StpUtil.getTokenInfo().tokenTimeout);

        return build;
    }

    /**
     * 是否是超级管理员
     * @return
     */
    public static boolean isAdmin(){
        return StrUtil.equals("1", get().getAdmin());
    }

}
